package com.hqd.ch03.v51.boot.web.filter;

import com.hqd.ch03.v51.web.http.HttpHeaders;
import com.hqd.ch03.v51.web.http.HttpStatus;
import com.hqd.ch03.v51.web.utils.WebUtils;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;

final class RelativeRedirectResponseWrapper extends HttpServletResponseWrapper {

    private final HttpStatus redirectStatus;


    private RelativeRedirectResponseWrapper(HttpServletResponse response, HttpStatus redirectStatus) {
        super(response);
        this.redirectStatus = redirectStatus;
    }

    public static HttpServletResponse wrapIfNecessary(HttpServletResponse response,
                                                      HttpStatus redirectStatus) {

        RelativeRedirectResponseWrapper wrapper =
                WebUtils.getNativeResponse(response, RelativeRedirectResponseWrapper.class);

        return (wrapper != null ? response :
                new RelativeRedirectResponseWrapper(response, redirectStatus));
    }

    @Override
    public void sendRedirect(String location) throws IOException {
        resetBuffer();
        setStatus(this.redirectStatus.value());
        setHeader(HttpHeaders.LOCATION, location);
        flushBuffer();
    }

}

